package com.demo.exception;

import com.demo.controller.UserController;
import com.demo.pojo.ret.RetResult;
import org.apache.ibatis.jdbc.Null;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;
import java.util.List;

@RestControllerAdvice(basePackageClasses={UserController.class})
public class ExceptionControllerAdvicer {
    @ExceptionHandler
    public RetResult<Null> handlerArgumentException(MethodArgumentNotValidException exception){
        RetResult<Null> retResult=new RetResult<>();
        retResult.setRetCode(400);
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<ObjectError> iterator = allErrors.iterator();
        while (iterator.hasNext()){
            stringBuilder.append(iterator.next().getDefaultMessage());
        }
        retResult.setRetMessage(stringBuilder.substring(0,stringBuilder.lastIndexOf(",")));
        return retResult;

    }

}
